package com.pdf.pdfserver.service.read.text;

import com.pdf.pdfserver.enums.FileSuffixEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Optional;

/**
 * @Author songfz
 * @Description
 * @Date 2022/1/4
 */
@Service
public class TxtReadService implements IfReadService {

    private static Logger LOG = LoggerFactory.getLogger(IfReadService.class);

    @Override
    public String read(FileSuffixEnum suffixEnum, InputStream in){

        InputStreamReader isr = null;
        BufferedReader fis = null;
        String code = "UTF-8";
        try {
            isr = new InputStreamReader(in,code);
            fis = new BufferedReader(isr);
            String linetxt;
            //result用来存储文件内容
            StringBuilder sb = new StringBuilder();
            //按使用readLine方法，一次读一行
            while ((linetxt = fis.readLine()) != null) {
                sb.append(linetxt);
            }
            return new String(sb.toString().getBytes(),code);
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        } finally {
            Optional.ofNullable(fis).ifPresent(fis1-> {
                try {
                    fis1.close();
                } catch (IOException e) {
                    LOG.error(e.getMessage(),e);
                }
            });
            Optional.ofNullable(isr).ifPresent(isr1-> {
                try {
                    isr1.close();
                } catch (IOException e) {
                    LOG.error(e.getMessage(),e);
                }
            });
            Optional.ofNullable(in).ifPresent(in1-> {
                try {
                    in1.close();
                } catch (IOException e) {
                    LOG.error(e.getMessage(),e);
                }
            });
        }

        return null;
    }
}
